<script setup lang="ts">
import { onMounted, ref, onBeforeUnmount, watchEffect } from 'vue';

const file = ref<File | null>(null);
const url = ref();

const emit = defineEmits<{
  (e: 'update:url', url: string): void;
}>();

function previewImage(input: HTMLInputElement) {
  if (input.files) {
    file.value = input.files[0];
  }
}

watchEffect((onCleanup) => {
  url.value = file.value ? URL.createObjectURL(file.value) : '';
  emit('update:url', url.value);
  onCleanup(() => {
    url.value && URL.revokeObjectURL(url.value);
  });
});

function openCamera() {
  document.getElementById('cameraInput')?.click();
}

function cameraInputChange(event: Event) {
  const inputElement = event.target as HTMLInputElement;
  previewImage(inputElement);
}

onMounted(() => {
  // 监听文件输入变化事件
  document.getElementById('cameraInput')?.addEventListener('change', cameraInputChange);
});

onBeforeUnmount(() => {
  document.getElementById('cameraInput')?.removeEventListener('change', cameraInputChange);
});
</script>
<template>
  <div class="OpenCamera">
    <!-- 拍照按钮 -->
    <input type="file" accept="image/*" capture="environment" id="cameraInput" style="display: none" />

    <!-- 拍照和选图触发按钮 -->
    <div @click.prevent="openCamera">
      <slot> 拍照 </slot>
    </div>
  </div>
</template>
